<template>
  <div class="dashboard-container">
    <!-- 时间筛选器 -->
    <a-row :gutter="20" class="mb-20">
      <a-col :span="24">
        <a-card class="filter-card">
          <div class="filter-header">
            <div class="filter-item">
              <span>时间范围：</span>
              <a-range-picker v-model:value="dateRange" />
            </div>
            <div class="filter-item">
              <span>时间粒度：</span>
              <a-radio-group v-model:value="timeGranularity" @change="onTimeGranularityChange">
                <a-radio-button value="day">按日</a-radio-button>
                <a-radio-button value="week">按周</a-radio-button>
                <a-radio-button value="month">按月</a-radio-button>
              </a-radio-group>
            </div>
            <div class="filter-item">
              <a-button type="primary" @click="exportData">导出数据</a-button>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="20" class="mb-20">
      <!-- 采/出量趋势图 -->
      <a-col :span="12">
        <a-card class="chart-card">
          <template #title>
            <span>采/出量趋势图</span>
          </template>
          <div class="chart-container">
            <div ref="trendChart" style="height: 300px;"></div>
          </div>
        </a-card>
      </a-col>
      
      <!-- 产品转化漏斗 -->
      <a-col :span="6">
        <a-card class="chart-card">
          <template #title>
            <span>产品转化漏斗</span>
          </template>
          <div class="chart-container">
            <div ref="funnelChart" style="height: 300px;"></div>
          </div>
        </a-card>
      </a-col>
      
      <!-- 接口调用统计 -->
      <a-col :span="6">
        <a-card class="chart-card">
          <template #title>
            <span>接口调用统计</span>
          </template>
          <a-tabs v-model:activeKey="interfaceTabKey">
            <a-tab-pane key="1" tab="成功率">
              <div ref="successRateChart" style="height: 250px;"></div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="耗时分布">
              <div ref="durationChart" style="height: 250px;"></div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>

    <!-- 数据明细 -->
    <a-row :gutter="20">
      <a-col :span="24">
        <a-card class="table-card">
          <template #title>
            <span>数据明细</span>
          </template>
          <div class="table-filter">
            <a-select v-model:value="statusFilter" style="width: 200px; margin-right: 20px;" allow-clear placeholder="请选择状态">
              <a-select-option value="success">成功</a-select-option>
              <a-select-option value="failure">失败</a-select-option>
            </a-select>
            <a-button @click="filterData">筛选</a-button>
          </div>
          <a-table 
            :data-source="tableData" 
            :columns="tableColumns" 
            :pagination="pagination"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="record.status === 'success' ? 'success' : 'error'">
                  {{ record.status === 'success' ? '成功' : '失败' }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { 
  UsergroupAddOutlined, 
  UserSwitchOutlined, 
  MoneyCollectOutlined, 
  TeamOutlined,
  BellOutlined
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';

export default {
  name: 'BusinessDashboard',
  components: {
    UsergroupAddOutlined,
    UserSwitchOutlined,
    MoneyCollectOutlined,
    TeamOutlined,
    BellOutlined
  },
  data() {
    return {
      dateRange: [dayjs().subtract(7, 'day'), dayjs()],
      timeGranularity: 'day',
      interfaceTabKey: '1',
      statusFilter: undefined,
      trendChart: null,
      funnelChart: null,
      successRateChart: null,
      durationChart: null,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 50
      },
      tableData: [
        { id: '1', userId: 'U10001', productId: 'P20001', time: '2023-09-01 10:30', status: 'success' },
        { id: '2', userId: 'U10002', productId: 'P20002', time: '2023-09-01 11:15', status: 'failure' },
        { id: '3', userId: 'U10003', productId: 'P20001', time: '2023-09-01 12:45', status: 'success' },
        { id: '4', userId: 'U10004', productId: 'P20003', time: '2023-09-01 14:20', status: 'failure' },
        { id: '5', userId: 'U10005', productId: 'P20002', time: '2023-09-01 15:30', status: 'success' },
        { id: '6', userId: 'U10006', productId: 'P20001', time: '2023-09-02 09:15', status: 'success' },
        { id: '7', userId: 'U10007', productId: 'P20003', time: '2023-09-02 10:45', status: 'failure' },
        { id: '8', userId: 'U10008', productId: 'P20002', time: '2023-09-02 13:20', status: 'success' },
        { id: '9', userId: 'U10009', productId: 'P20001', time: '2023-09-02 15:10', status: 'success' },
        { id: '10', userId: 'U10010', productId: 'P20003', time: '2023-09-02 16:30', status: 'failure' }
      ],
      tableColumns: [
        {
          title: 'ID',
          dataIndex: 'id',
          key: 'id',
          width: 80
        },
        {
          title: '用户ID',
          dataIndex: 'userId',
          key: 'userId',
          width: 120
        },
        {
          title: '产品ID',
          dataIndex: 'productId',
          key: 'productId',
          width: 120
        },
        {
          title: '时间',
          dataIndex: 'time',
          key: 'time',
          width: 180
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 100
        }
      ]
    }
  },
  mounted() {
    this.initCharts()
  },
  beforeUnmount() {
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    if (this.funnelChart) {
      this.funnelChart.dispose();
    }
    if (this.successRateChart) {
      this.successRateChart.dispose();
    }
    if (this.durationChart) {
      this.durationChart.dispose();
    }
  },
  methods: {
    onTimeGranularityChange(e) {
      console.log('时间粒度切换到:', e.target.value);
      this.initCharts();
    },
    initCharts() {
      this.$nextTick(() => {
        this.initTrendChart();
        this.initFunnelChart();
        this.initSuccessRateChart();
        this.initDurationChart();
      });
    },
    initTrendChart() {
      const trendChartDom = this.$refs.trendChart;
      if (!trendChartDom) return;
      
      if (this.trendChart) {
        this.trendChart.dispose();
      }
      
      this.trendChart = echarts.init(trendChartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['采量', '出量']
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.timeGranularity === 'day' 
            ? ['09-01', '09-02', '09-03', '09-04', '09-05', '09-06', '09-07'] 
            : this.timeGranularity === 'week' 
              ? ['第1周', '第2周', '第3周', '第4周'] 
              : ['1月', '2月', '3月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '采量',
            type: 'line',
            data: this.timeGranularity === 'day' 
              ? [120, 132, 101, 134, 90, 230, 210] 
              : this.timeGranularity === 'week' 
                ? [400, 520, 450, 600] 
                : [1500, 1800, 2100],
            smooth: true,
            areaStyle: {
              opacity: 0.2
            },
            lineStyle: {
              width: 2
            }
          },
          {
            name: '出量',
            type: 'line',
            data: this.timeGranularity === 'day' 
              ? [100, 112, 91, 114, 80, 200, 180] 
              : this.timeGranularity === 'week' 
                ? [350, 450, 380, 520] 
                : [1200, 1500, 1700],
            smooth: true,
            areaStyle: {
              opacity: 0.2
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      };
      
      this.trendChart.setOption(option);
    },
    initFunnelChart() {
      const funnelChartDom = this.$refs.funnelChart;
      if (!funnelChartDom) return;
      
      if (this.funnelChart) {
        this.funnelChart.dispose();
      }
      
      this.funnelChart = echarts.init(funnelChartDom);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}%'
        },
        legend: {
          data: ['注册', '下载', '实名', '授信', '开通积分会员', '申请现金业务', '放款成功']
        },
        series: [
          {
            name: '转化率',
            type: 'funnel',
            left: '10%',
            top: 60,
            bottom: 60,
            width: '80%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              position: 'inside'
            },
            labelLine: {
              length: 10,
              lineStyle: {
                width: 1,
                type: 'solid'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1
            },
            emphasis: {
              label: {
                fontSize: 14
              }
            },
            data: [
              { value: 100, name: '注册' },
              { value: 85, name: '下载' },
              { value: 70, name: '实名' },
              { value: 60, name: '授信' },
              { value: 45, name: '开通积分会员' },
              { value: 30, name: '申请现金业务' },
              { value: 20, name: '放款成功' }
            ]
          }
        ]
      };
      
      this.funnelChart.setOption(option);
    },
    initSuccessRateChart() {
      const successRateChartDom = this.$refs.successRateChart;
      if (!successRateChartDom) return;
      
      if (this.successRateChart) {
        this.successRateChart.dispose();
      }
      
      this.successRateChart = echarts.init(successRateChartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['接口A', '接口B', '接口C', '接口D', '接口E']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            name: '成功率',
            type: 'bar',
            barWidth: '60%',
            data: [98, 85, 92, 95, 88],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
          }
        ]
      };
      
      this.successRateChart.setOption(option);
    },
    initDurationChart() {
      const durationChartDom = this.$refs.durationChart;
      if (!durationChartDom) return;
      
      if (this.durationChart) {
        this.durationChart.dispose();
      }
      
      this.durationChart = echarts.init(durationChartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['<100ms', '100-200ms', '200-500ms', '500-1000ms', '>1000ms']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '耗时分布',
            type: 'bar',
            barWidth: '60%',
            data: [20, 35, 25, 15, 5],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#fcc006' },
                { offset: 0.5, color: '#f59e00' },
                { offset: 1, color: '#f59e00' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#f59e00' },
                  { offset: 0.7, color: '#f59e00' },
                  { offset: 1, color: '#fcc006' }
                ])
              }
            }
          }
        ]
      };
      
      this.durationChart.setOption(option);
    },
    filterData() {
      console.log('筛选数据，状态:', this.statusFilter);
      message.success('数据筛选成功');
    },
    handleTableChange(pagination) {
      console.log('表格分页变化:', pagination);
      this.pagination.current = pagination.current;
    },
    exportData() {
      message.success('数据导出成功');
      console.log('导出数据');
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.filter-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.filter-item {
  margin-right: 30px;
  display: flex;
  align-items: center;
}

.filter-item span {
  margin-right: 10px;
  white-space: nowrap;
}

.dashboard-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 15px;
}

.bg-primary {
  background-color: #1890ff;
}

.bg-success {
  background-color: #52c41a;
}

.bg-warning {
  background-color: #faad14;
}

.bg-danger {
  background-color: #f5222d;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.card-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.change-rate {
  font-size: 14px;
  margin-left: 5px;
}

.change-rate.positive {
  color: #52c41a;
}

.change-rate.negative {
  color: #f5222d;
}

.card-sub {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.chart-card,
.table-card,
.alert-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.alert-container {
  height: 300px;
  overflow-y: auto;
}

.alert-item {
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.alert-item:hover {
  background-color: #f5f5f5;
}

.alert-content {
  margin-left: 10px;
  flex: 1;
}
</style>